package com.bigdata.common.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

public class CaptchaUtil {
    // 存储验证码的Map，key是sessionId，value是验证码+过期时间的组合（格式：captchaText|expireTimestamp）
    private static final ConcurrentHashMap<String, String> captchaMap = new ConcurrentHashMap<>();
    // 验证码有效期（毫秒），这里设置为5分钟
    private static final long CAPTCHA_EXPIRE_TIME = 5 * 60 * 1000;

    /**
     * 生成4位随机验证码
     */
    public static String generateCaptchaText() {
        String chars = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }
        return sb.toString();
    }

    /**
     * 生成验证码图片
     */
    public static byte[] generateCaptchaImage(String captchaText) throws IOException {
        int width = 100;
        int height = 40;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取图形上下文
        Graphics g = image.getGraphics();

        // 设定背景色
        g.setColor(getRandColor(200, 250));
        g.fillRect(0, 0, width, height);

        // 设定字体
        g.setFont(new Font("Times New Roman", Font.PLAIN, 20));

        // 随机产生干扰线
        for (int i = 0; i < 155; i++) {
            int x = randomInt(0, width);
            int y = randomInt(0, height);
            int xl = randomInt(1, 10);
            int yl = randomInt(1, 10);
            g.setColor(getRandColor(160, 200));
            g.drawLine(x, y, x + xl, y + yl);
        }

        // 画验证码
        String captchaChars = captchaText;
        for (int i = 0; i < captchaChars.length(); i++) {
            g.setColor(new Color(20 + randomInt(0, 100), 20 + randomInt(0, 100),
                    20 + randomInt(0, 100)));
            g.drawString(captchaChars.charAt(i) + "", i * 20 + 6, 26);
        }

        // 释放图形上下文
        g.dispose();

        // 转换为字节数组
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bos);
        return bos.toByteArray();
    }

    private static Random random = new Random();

    private static int randomInt(int min, int max) {
        return random.nextInt(max - min) + min;
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255) fc = 255;
        if (bc > 255) bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    /**
     * 存储验证码（包含过期时间）
     */
    public static void storeCaptcha(String sessionId, String captchaText) {
        long expireTime = System.currentTimeMillis() + CAPTCHA_EXPIRE_TIME;
        captchaMap.put(sessionId, captchaText + "|" + expireTime);
    }

    /**
     * 获取验证码（不包含过期时间）
     */
    public static String getCaptcha(String sessionId) {
        String value = captchaMap.get(sessionId);
        if (value == null) {
            return null;
        }
        return value.split("\\|")[0];
    }

    /**
     * 验证验证码是否正确且未过期
     */
    public static boolean validateCaptcha(String sessionId, String userInput) {
        String value = captchaMap.get(sessionId);
        if (value == null) {
            return false; // 验证码不存在或已过期
        }

        String[] parts = value.split("\\|");
        if (parts.length != 2) {
            return false; // 数据格式错误
        }

        String correctCaptcha = parts[0];
        long expireTime = Long.parseLong(parts[1]);

        // 检查是否过期
        if (System.currentTimeMillis() > expireTime) {
            captchaMap.remove(sessionId); // 清除过期验证码
            return false;
        }

        // 验证验证码
        boolean isValid = correctCaptcha.equalsIgnoreCase(userInput);
        if (isValid) {
            captchaMap.remove(sessionId); // 验证成功后清除
        }
        return isValid;
    }

    /**
     * 清除验证码（手动调用）
     */
    public static void removeCaptcha(String sessionId) {
        captchaMap.remove(sessionId);
    }
}
